package acs.offer.client;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;

import acs.offer.collection.Params;
import acs.offer.constant.Constant;
import acs.offer.constant.EventType;
import acs.offer.pojo.Message;
import acs.offer.pojo.RequestEnum;
import acs.offer.pojo.TranstractDate;
import acs.offer.util.CacheUtil;
import acs.offer.util.CollectionUtil;
import acs.offer.util.NettyRequestUtil;
import acs.offer.util.SoftTimer;

public class ClientTask {
	private static final int STATE_INIT = 1;
	private static final int STATE_WAITING_OFFER = 2;// 加载数据中
	private static final int STATE_DATA_LOADED = 4;
	private int currentState = STATE_INIT;// 状态
	private String type;
	
	
	
	public void handleTargetOfferResponse(Params param) {
		if(currentState == STATE_WAITING_OFFER) {
			Map<String,Object> offerMap = param.get(Constant.TRANSFER_OFFER);
			if(CollectionUtil.isEmpty(offerMap)) {
				System.out.println("没有查到offers");
				return ;
			}
			CacheUtil.getInstance().saveCache(this.type,offerMap);
			this.currentState = STATE_DATA_LOADED;// 设置当前状态为查到了offer
		}
	}

	public void loadCache(Params param) {
		if (currentState == STATE_INIT) {
			TranstractDate requestData = TranstractDate.build();
			requestData.setRequestEnum(RequestEnum.REQUEST_OFFER);
			param.put("duration", 2);
			param.put("timeUnit", TimeUnit.SECONDS);

			requestData.setData(param);
			Message message = Message.build(JSON.toJSONString(requestData));
			NettyRequestUtil.request(message);

			SoftTimer.getInstance().startTimer(10 * 1000, EventType.TIMEOUT_WHEN_GET_TARGET_OFFER);
			// 设置超时
			this.currentState = STATE_WAITING_OFFER;
			return ;
		}
		System.out.println("不用再请求服务端了。。。");
	}
	public void handleTargetOfferTimeOut(Params param) {
		switch (currentState) {
		case STATE_WAITING_OFFER:
			System.out.println("请求服务端offer超时了");
			this.currentState=STATE_INIT;
			break;
		case STATE_DATA_LOADED:
			System.out.println("请求服务端offer成功，不进行取消请求offer任务");
			break;
		}
		
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
	
	
}
